package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScanFree;
import com.heima.common.aliyun.GreenTextScanFree;
import com.heima.common.aliyun.OssTemplate;
import com.heima.common.exception.CustomException;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
//import com.heima.wemedia.service.WmNewsTaskService;
//import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenTextScanFree greenTextScanFree;

    @Autowired
    private GreenImageScanFree greenImageScanFree;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IArticleClient iArticleClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @Autowired
    private Tess4jClient tess4jClient;


    /**
     * 自媒体文章审核
     * @param id 自媒体文章id
     */
    @Override
    @Async //标明当前方法是一个异步方法
    //@GlobalTransactional seata
    public void autoScanWmNews(Integer id) {
        //1.检验参数
        if(id == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.根据自媒体文章id查询文章
        WmNews wmNews = wmNewsMapper.selectOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId,id));
        if(wmNews == null){
            throw  new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.获取文章内容
        String content = wmNews.getContent();
        if(content.isEmpty()){
            throw  new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //4.提取文章内容的文本和图片信息
        if(wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            Map<String,Object> resultMap = handleTextAndImages(wmNews);
            if(resultMap == null){
                throw  new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //5.审核文本和图片信息
            //5.1 文本审核
            Boolean isTextScan = handleTextScan((String) resultMap.get("content"),wmNews);
            if(!isTextScan)return;
            //自管理文章审核
            Boolean isSensitiveScan = handleSensitiveScan((String) resultMap.get("content"),wmNews);
            if(!isSensitiveScan)return;
            //5.2 图片审核
            Boolean isImageScan = handleImageScan((List<String>) resultMap.get("images"),wmNews);
            if(!isImageScan)return;
            //6.审核成功，保存app端的相关的文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);
            if(!responseResult.getCode().equals(200)){
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
            }
            //回填article_id
            wmNews.setArticleId((Long) responseResult.getData()) ;
            updateWmNews(wmNews,WmNews.Status.PUBLISHED.getCode(),"审核成功");
        }
    }

    /**
     * 自管理文章审核
     * @param content
     * @param wmNews
     * @return
     */
    private Boolean handleSensitiveScan(String content, WmNews wmNews) {
        boolean flag = true;
        //查询所有敏感词,只包含一个字段
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);
        //查看文章中是否包含敏感词
        Map<String,Integer> wordMap = SensitiveWordUtil.matchWords(content);
        if(wordMap.size() > 0){
            flag = false;
            updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"当前文章中存在违规内容："+wordMap);
        }
        return flag;
    }


    /**
     * 保存app端相关的文章数据
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {

        ArticleDto dto = new ArticleDto();
        //属性的拷贝
        BeanUtils.copyProperties(wmNews,dto);
        //文章的布局
        dto.setLayout(wmNews.getType());
        //频道名称
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(wmChannel != null){
            dto.setChannelName(wmChannel.getName());
        }
        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser != null){
            dto.setAuthorName(wmUser.getName());
        }
        //设置为章id
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());

        ResponseResult responseResult = iArticleClient.saveArticle(dto);
        return responseResult;

    }

    /**
     * 审核图片
     * @param images
     * @param wmNews
     * @return
     */
    private Boolean handleImageScan(List<String> images, WmNews wmNews) {
        Boolean flag = true;
        if(!images.isEmpty() && images.size() > 0){
            //图片去重
            images = images.stream().distinct().collect(Collectors.toList());
            for (String url : images) {
                try {
                    //图片文字审核
                    byte[] bytes  = fileStorageService.downLoadFile(url);
                    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                    BufferedImage imageFile = ImageIO.read(in);
                    //当图片是不包含文字的类型，imageFile可能为null
                    if(imageFile != null){
                        String imageTextResult = tess4jClient.doOCR(imageFile);
                        //过滤文字
                        Boolean isSensitiveScan = handleSensitiveScan(imageTextResult,wmNews);
                        if(!isSensitiveScan){
                            return isSensitiveScan;
                        }
                        Boolean isTextScan = handleTextScan(imageTextResult,wmNews);
                        if(!isTextScan){
                            return isTextScan;
                        }
                    }
                    //审核图片
                    InputStream inputStream = fileStorageService.downLoadFileFree(url);
                    url = ossTemplate.upload(url,inputStream);
                    Map imageResultMap = greenImageScanFree.greenImageScanFree(url);
                    ossTemplate.delete(url);
                    if(imageResultMap != null){
                        if(imageResultMap.get("suggestion").equals("block")){
                            flag = false;
                            updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"当前文章中存在违规内容");
                        }
                        if(imageResultMap.get("suggestion").equals("review")){
                            flag = false;
                            updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"文章内容中有不确定内容");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 审核纯文本内容
     * @param contentText
     * @param wmNews
     * @return
     */
    private Boolean handleTextScan(String contentText, WmNews wmNews) {
        boolean flag = true;
        if(StringUtils.isNotBlank(contentText) && StringUtils.isNotBlank(wmNews.getTitle())){
            try {
                Map textResultMap = greenTextScanFree.greenTextScan(wmNews.getTitle()+'-'+contentText);
                if(textResultMap != null){
                    if(textResultMap.get("suggestion").equals("block")){
                        flag = false;
                        updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"当前文章中存在违规内容");

                    }
                    if(textResultMap.get("suggestion").equals("review")){
                        flag = false;
                        updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"文章内容中有不确定内容");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 修改文章内容
     * @param wmNews
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 1.从自媒体文章的内容中提取文本和图片
     * 2.提取文章的封面图片
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //1.从文章内容中提取文本和图片
        //存储纯文本内容
        StringBuilder stringBuilder = new StringBuilder();
        List<String> images = new ArrayList<>();
        String content = wmNews.getContent();
        if(StringUtils.isNotBlank(content)) {
            List<Map> maps = JSON.parseArray(content, Map.class);
            for (Map map : maps) {
                //1.1 提取文本
                if (map.get("type").equals("text")) {
                    stringBuilder.append(map.get("value"));
                }
                //1.2 提取图片
                if (map.get("type").equals("image")) {
                    String imageUrl = (String) map.get("value");
                    images.add(imageUrl);
                }
            }
        }
        //2.提取文章的封面图片
        if(StringUtils.isNotBlank(wmNews.getImages())){
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }
        //构造返回结果
        Map<String,Object> resultMap = new HashMap();
        resultMap.put("content",stringBuilder.toString());
        resultMap.put("images",images);
        return resultMap;
    }
}
